package com.bgq.trxpay.controller;

import com.alibaba.fastjson2.JSONObject;
import com.bgq.trxpay.mapper.MessageRecordMapper;
import com.bgq.trxpay.mapper.PayRecordMapper;
import com.bgq.trxpay.model.MessageRecord;
import com.bgq.trxpay.model.PayRecord;
import jdk.nashorn.internal.parser.JSONParser;
import kafka.utils.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ExecutionException;

@RestController
public class DataController {


    @Autowired
    private PayRecordMapper payRecordMapper;

    @Autowired
    private MessageRecordMapper messageRecordMapper;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @GetMapping(value = "/addAuthTrx")
    public String addAuthTrx() {
        String authCode = "chl";
        String userId = "a-001";
        // add pay
        PayRecord payRecord = new PayRecord();
        long payId = new Random().nextLong();
        if (payId < 0) {
            payId = payId * -1;
        }
        payRecord.setId(payId);
        payRecord.setPayAmount("1.12");
        payRecord.setPayStatus("ok");
        payRecord.setAuthCode(authCode);
        payRecord.setCreateTime(new Date());
        payRecord.setUpdateTime(new Date());
        payRecord.setUserId(userId);
        payRecordMapper.insert(payRecord);

        // add message record (trx_status = 0 进行中)
        MessageRecord messageRecord = new MessageRecord();
        long msgId = new Random().nextLong();
        if (msgId < 0) {
            msgId = msgId * -1;
        }
        messageRecord.setId(msgId);
        messageRecord.setTrxId("0");
        messageRecord.setPayRecordRefId(payId+"");
        messageRecord.setTrxStatus("0");
        messageRecord.setCreateTime(new Date());
        messageRecord.setUpdateTime(new Date());
        messageRecordMapper.insert(messageRecord);

        // send kafka
        Map<String, Object> msgMap = new HashMap<>();
        msgMap.put("authCode", authCode);
        msgMap.put("userId", userId);
        msgMap.put("payId", payId);
        msgMap.put("msgId", msgId);
        kafkaTemplate.send("cat", JSONObject.from(msgMap).toString());

        return "addAuthTrx ok; (adding auth...)";
    }

}
